package com.zyy.seckill.rabbitmq;

import com.zyy.seckill.config.RabbitmqConfig;
import com.zyy.seckill.entity.SeckillOrder;
import com.zyy.seckill.entity.User;
import com.zyy.seckill.service.IGoodsService;
import com.zyy.seckill.service.IOrderService;
import com.zyy.seckill.utils.JsonUtil;
import com.zyy.seckill.vo.GoodsVo;
import com.zyy.seckill.vo.SeckillMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @Author: zyy
 * @DateTime: 2021/10/5 19:33
 */
@Service
@Slf4j
public class MQReceiver {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;

    /**
     *   下单操作
     * @param message
     */
    @RabbitListener(queues = RabbitmqConfig.QUEUE_NAME)
    public void consumer(String message){
        ValueOperations valueOperations = redisTemplate.opsForValue();

        log.info(" 接收到的信息为: "+message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodId();
        User user = seckillMessage.getUser();

        // 通过商品id获取秒杀商品库存
        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        if (goodsVo.getStockCount()<1){
            return;
        }
        // 判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) valueOperations.
                get("order:" + user.getId() + ":" + goodsId);

        if (seckillOrder != null) {
            return;
        }

        // 开始下单
        orderService.seckill(user,goodsVo);

    }
}
